import pyecharts.charts as pch
import pyecharts.options as opts
import pandas as pd
import streamlit as st
import streamlit_echarts
from streamlit_echarts import st_echarts

# bar = (
#     pch.Bar()
#     .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
#     .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
#     .add_yaxis("商家B", [15, 6, 45, 20, 65, 55])
#     .set_global_opts(title_opts=opts.TitleOpts(title="柱状图示例"))
# )
# streamlit_echarts.st_pyecharts(
#     bar,
#     # theme=ThemeType.DARK
# )
# bar_html = bar.render_embed()
# st.write(bar_html,unsafe_allow_html=True)
# # 或者直接在 Streamlit 中显示

from pyecharts.charts import Map
from pyecharts import options as opts
from pyecharts.globals import ThemeType, CurrentConfig
import requests
import time

headers = {
    'authority': 'weibo.com',
    'x-requested-with': 'XMLHttpRequest',
    'sec-ch-ua-mobile': '?0',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded',
    'accept': '*/*',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://weibo.com/1192329374/KnnG78Yf3?filter=hot&root_comment_id=0&type=comment',
    'accept-language': 'zh-CN,zh;q=0.9,en-CN;q=0.8,en;q=0.7,es-MX;q=0.6,es;q=0.5',
    'cookie': 'XSRF-TOKEN=ZYaTd1QfIFhVQ9pYAMSL1psM; PC_TOKEN=d21cd95cde; '
              'SCF=Ang1PsM9AoPOH6r2JMfsf_cG-DF5ce8cSUt-u4AhK1i5jJiWuB6_FFQ4pasglzYVBhChL7yD8F2XddVlTzUxnfk.; '
              'SSOLoginState=1704105487; '
              'SUB=_2A25IluZfDeRhGeNI7FEQ-CbIyD2IHXVr6meXrDV8PUJbkNAGLUr9kW1NSCMrRlDQJVwj6AUDLALQ5pufur-YqtJ4; '
              'SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WWSJ_7WUJKD_-HWMMWH1YY_5NHD95QfSoM0eKnRShepWs4Dqcj.i--ciK.RiKLsi'
              '--fiKnfiKn4i--fi-i8i-88i--ci-82i-2f; '
              'WBPSESS=Dt2hbAUaXfkVprjyrAZT_PVjiE3miJhLtfrcwCT2D6FzV7D7_aoIlMSrBi2l8-ZzoM91k1vTEfjfh7udYw5'
              '-CdEoQLoVtFQnWWA-BHiTE4VIuaHL_xPvKQKze1FB1WAM_Rndnd79MEWVrQ8OXInVg1U0ny'
              '-VxmGIhkUOb3AZ5NO5uFk0a9GgL3hTunkNo3wNUrQe60FgROB4mI9kwGvH3A=='
}


def getIPlocation(uid):
    response = requests.get(url=f'https://weibo.com/ajax/profile/detail?uid={uid}', headers=headers)
    resp_json = response.json().get('data', None)
    if not resp_json:
        return None
    ip_location = resp_json.get('ip_location', None)
    ip_locationRes = ''
    if ip_location == None:
        return None
    if '：' in ip_location:
        ip_locationRes = ip_location.split('：')[1]
    else:
        ip_locationRes = ip_location
    return ip_locationRes


# df = pd.read_csv('./结果文件/董宇辉/董宇辉.csv')
# # 开始时间
# start_time = time.time()
# df['ip_location'] = df['user_id'].apply(lambda x:getIPlocation(x))
# # 结束时间
# end_time = time.time()
# df.to_csv('./结果文件/董宇辉/董宇辉_ip_location.csv', index=False)
# # 打印结束时间和开始时间之差，转换为秒
# print('程序运行时间：', end_time - start_time)
df = pd.read_csv('./结果文件/董宇辉/董宇辉_ip_location.csv')

data = df['ip_location'].value_counts()
datas = [(i, int(j)) for i, j in zip(data.index, data.values)]
# map_ = Map(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION))
#
# # 世界地图
# map_.add(series_name="博文数量", data_pair=datas, maptype="china")
#
# # 设置系列配置项
# map_.set_series_opts(label_opts=opts.LabelOpts(is_show=False))  # 不显示label
# # 设置全局配置项
# map_.set_global_opts(
#     title_opts=opts.TitleOpts(title="发博数量在全国分布",
#                               pos_left='40%',
#                               pos_top='10'),  # 调整title位置
#     legend_opts=opts.LegendOpts(is_show=False),
#     visualmap_opts=opts.VisualMapOpts(
#         max_=13608,
#         min_=1,
#         is_piecewise=True,
#         pieces=[{"max": 9, "min": 1, "label": "1-9", "color": "#00FFFF"},
#                 {"max": 99, "min": 10, "label": "10-99", "color": "#FF69B4"},
#                 {"max": 499, "min": 100, "label": "100-499", "color": "#0000FF"},
#                 {"max": 999, "min": 500, "label": "500-999", "color": "#00BFFF"},
#                 {"max": 2000, "min": 1000, "label": "1000-2000", "color": "#228B22"},
#                 {"max": 3000, "min": 2000, "label": "2000-3000", "color": "#FF0000"},
#                 {"max": 20000, "min": 10000, "label": ">=10000", "color": "#FFD700"}
#                 ]  # 分段  添加图例注释和颜色
#     )
# )
# print(datas)
# map_.render('博文数量在全国的分布.html')
# streamlit_echarts.st_pyecharts(map_)
import json


def map_province(data0):
    # with open(r"F:\notebooks1\streamlit\echarts-map-master\echarts-4.2.1-rc1-map\json\china.json", "r",
    #           encoding="utf-8") as f:
    map = Map(
        "china",
        # json.loads(f.read())
    )

    options = {
        "tooltip": {
            "trigger": 'item',
            "showDelay": 0,
            "transitionDuration": 0.2,
        },
        "visualMap": {
            "show": False,
            "left": "right",
            "min": 0,
            "max": 2500,
            "inRange": {
                "color": [
                    "#313695",
                    "#4575b4",
                    "#74add1",
                    "#abd9e9",
                    "#e0f3f8",
                    "#ffffbf",
                    "#fee090",
                    "#fdae61",
                    "#f46d43",
                    "#d73027",
                    "#a50026",
                ]
            },
            "text": ["High", "Low"],
            "calculable": True,
        },
        "series": [
            {
                "name": "商品数量地域分布",
                "type": "map",
                "roam": True,
                "map": "china",
                "emphasis": {"label": {"show": True}},
                "data": data0,
            }
        ],
    }

    events = {
        "click": "function(params) {return params.name }",
    }
    return options, map, events


data_province = []
for i in df['ip_location'].items():
    data_province.append({"name": i[0], "value": i[1]})

# province_pinyin={"浙江":"zhejiang","福建":"fujian","安徽":"anhui"}

option_province, map_province, events_province = map_province(data_province)

province = st_echarts(option_province, map=map_province, events=events_province)
